<template>
  <view class="comment-page">
    <view class="tab-wrapper">
      <view class="tab-container">
        <view
          v-for="(tab, index) in tabs"
          :key="index"
          class="tab-item"
          :class="{ active: activeTab === tab.value }"
          @click="handleTabChange(tab.value)">
          <text>{{ tab.label }}</text>
          <text v-if="tab.count">({{ tab.count }})</text>
        </view>
      </view>
    </view>

    <view class="comment-list">
      <view
        v-for="(comment, commentIndex) in filteredComments"
        :key="commentIndex"
        class="comment-item">
        <view class="comment-header">
          <view class="header-left">
            <!-- <image
              :src="comment.userAvatar"
              style="
                width: 30px;
                height: 30px;
                margin-right: 5px;
                background-color: #ccc;
                border-radius: 30px;
              "></image> -->
            <text class="userName">{{ comment.userName }}</text>
          </view>
          <text class="commentTime">
            {{ formatDate(comment.commentTime, "yyyy-MM-dd hh:mm:ss") }}
          </text>
        </view>
        <uni-rate
          allow-half
          :value="comment.score"
          :count="5"
          active-color="#ff8a3c"
          inactive-color="#f5f5f5"
          readonly
          size="24" />
        <!-- <text class="content">{{ comment.content }}</text> -->
        <view
          v-if="comment.images && comment.images.length > 0"
          class="comment-images">
          <image
            v-for="(img, imgIndex) in comment.images"
            :key="imgIndex"
            :src="completeImgPath(img)"
            @click="previewImage(completeImgPath(img))"
            class="comment-img" />
        </view>
        <view class="comment-actions" v-if="isAdmin">
          <text
            v-if="comment.status == 'pending'"
            class="action-btn pass"
            @click="handlePass(comment)">
            通过
          </text>
          <text class="action-btn delete" @click="handleDelete(comment)">
            删除
          </text>
        </view>
      </view>
    </view>
    <view class="hasMore" v-if="isHasMore" @click="checkMore()">
      查看更多留言
    </view>
    <view class="notMore" v-else>暂无留言</view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted } from "vue";
import API from "@/api/index.js";
import { completeImgPath, formatDate } from "@/utils/common.js";

const tabs = ref([
  { value: "all", label: "全部留言", count: 0 },
  // { value: 'hasImg', label: '有图', count: 0 },
]);

const isHasMore = ref(true);
const isAdmin = ref(false);

// 组件属性定义
const props = defineProps({
  id: {
    type: String,
  },
});

const pageData = ref({
  page: 1,
  pageSize: 10,
});

// 激活的标签值
const activeTab = ref("all");

const hasImg = ref(false);

const comments = ref([]);

const getCommentList = async () => {
  if (!props.id) {
    return;
  }
  let params = {
    page: pageData.value.page,
    pageSize: pageData.value.pageSize,
    productId: props.id,
  };
  if (!isAdmin.value) {
    params.status = "approved";
  }
  const res = await API.comment.getCommentListApi(params);
  if (res.success) {
    comments.value.push(...res.data.items);
    tabs.value[0].count = res.data.meta.totalItems;
    if (comments.value.length == tabs.value[0].count) {
      isHasMore.value = false;
    }
    if (res.data.items.length < pageData.value.pageSize) {
      isHasMore.value = false;
    }
  }
};

onMounted(async () => {
  const storedUser = uni.getStorageSync("adminUser");
  if (storedUser) {
    isAdmin.value = true;
  }
  await getCommentList();
});

const filteredComments = computed(() => {
  let result = [...comments.value];
  // 这里可以根据 activeTab 和 hasImg 进行更复杂的筛选逻辑
  return result;
});

const handleTabChange = (value) => {
  activeTab.value = value;
  if (value == "all") {
    comments.value.length = 0;
    pageData.value.page = 1;
    getCommentList();
  }
};

const previewImage = (url: string) => {
  let imgsArray = [];
  imgsArray[0] = url;
  uni.previewImage({
    current: 0,
    urls: imgsArray,
  });
};

const checkMore = async () => {
  pageData.value.page++;
  await getCommentList();
};

const handlePass = async (item) => {
  uni.showModal({
    title: "通过",
    content: "确定通过当前留言",
    success: async (res) => {
      if (res.confirm) {
        // 用户点击了确定按钮，执行跳转等操作
        console.log("用户点击确定,id=", item._id);
        const res = await API.comment.updateCommentInfoByIdApi(item._id, {
          status: "approved",
        });
        if (res.success) {
          uni.showToast({
            title: "审批成功",
            icon: "success",
          });
          comments.value.forEach((elem) => {
            if (elem._id == item._id) {
              elem.status = "approved";
            }
          });
        } else {
          uni.showToast({
            title: "审批失败",
            icon: "error",
          });
        }
      }
    },
  });
};

const handleDelete = async (item) => {
  uni.showModal({
    title: "删除",
    content: "确定删除当前留言",
    success: async (res) => {
      if (res.confirm) {
        // 用户点击了确定按钮，执行跳转等操作
        console.log("用户点击确定,id=", item._id);
        const res = await API.comment.deleteCommentInfoByIdApi(item._id);
        if (res.success) {
          uni.showToast({
            title: "删除成功",
            icon: "success",
          });
          comments.value = comments.value.filter((elem) => {
            return elem._id !== item._id;
          });
        } else {
          uni.showToast({
            title: "删除失败",
            icon: "error",
          });
        }
      }
    },
  });
};
</script>

<style scoped lang="scss">
.comment-page {
  padding: 10px;
}

.tab-wrapper {
  overflow-x: auto; // 允许横向滚动
  -webkit-overflow-scrolling: touch; // 苹果设备流畅滚动
  border-bottom: 1px solid #e5e5e5;
  padding: 8px 0;

  // 隐藏滚动条（各端兼容）
  &::-webkit-scrollbar {
    display: none;
  }
  -ms-overflow-style: none;
  scrollbar-width: none;

  .tab-container {
    display: flex;
    gap: 16px; // 标签间间距
    padding: 0 10px; // 左右内边距，避免顶边
    white-space: nowrap; // 防止换行
  }

  .tab-item {
    padding: 6px 12px; // 内边距，让点击区域更大
    font-size: 14px;
    cursor: pointer;
    border-radius: 16px; // 圆角，更柔和
    transition: all 0.3s ease;
    background-color: #f5f5f5; // 未激活背景
    color: #666; // 未激活文字色

    // 激活状态
    &.active {
      background-color: #fff3eb; // 示例橙色背景
      color: #ff8a3c; // 示例橙色文字
      font-weight: 500;
    }
  }

  .tab-count {
    font-size: 12px;
    color: #999;
    margin-left: 4px;
  }
}

.comment-list {
  padding: 10px;
  .comment-item {
    margin-bottom: 10px;
    padding: 10px;
    border-bottom: 1px solid #eee;
    position: relative;
    background-color: #fffcf752;
  }
  .comment-item::before {
    content: ""; /* 伪元素必须有 content，空值即可 */
    position: absolute; /* 绝对定位 */
    left: 0; /* 定位到元素最左侧 */
    top: 0; /* 顶部对齐 */
    bottom: 0; /* 底部对齐，实现高度与父元素一致 */
    width: 3px; /* 竖杠宽度 */
    background-color: #ff8a3c; /* 竖杠颜色 */
    border-radius: 1px; /* 可选：让竖杠边缘更圆润 */
  }

  .comment-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 8px;
    .header-left {
      display: flex;
      align-items: center;
    }
  }

  .avatar {
    width: 30px;
    height: 30px;
    border-radius: 50%;
    margin-right: 8px;
  }

  .userName {
    font-weight: bold;
    margin-right: 8px;
  }

  .commentTime {
    font-size: 12px;
    color: #999;
  }

  .content {
    display: block;
    margin: 5px 5px;
    line-height: 1.5;
    word-wrap: break-word;
  }

  .comment-images {
    display: flex;
    margin-bottom: 10px;
  }

  .comment-img {
    width: 80px;
    height: 80px;
    margin-right: 10px;
    border-radius: 4px;
  }
  .comment-actions {
    display: flex;
    justify-content: flex-end; // 按钮居右
    gap: 10px;
  }

  .action-btn {
    padding: 5px 10px;
    border-radius: 4px;
    font-size: 14px;
    border: none;
    color: #fff;
  }

  .pass {
    background-color: #4cd964; // 绿色通过按钮
  }

  .delete {
    background-color: #ff3b30; // 红色删除按钮
  }
}

.hasMore {
  width: 100%;
  text-align: center;
  color: #ff8a3c;
}
.notMore {
  width: 100%;
  text-align: center;
  color: #ff8a3c;
}
</style>
